package logic.nodes.lod;

import logic.nodes.BoundController;
import logic.nodes.ModelNode;
import logic.nodes.TeamNode;
import map.asteroids.Asteroid;
import map.spawnStation.SpawnStation;
import fileHandling.TextureLoader;

import com.jme.bounding.BoundingBox;
import com.jme.renderer.Renderer;
import com.jme.scene.BillboardNode;
import com.jme.scene.Spatial.LightCombineMode;
import com.jme.scene.shape.Quad;
import com.jme.scene.state.BlendState;
import com.jme.system.DisplaySystem;

public class BBNodeController extends BoundController {
	
	private static final long serialVersionUID = 1L;
	
	public static final String ICON_FILE = "/icon.png";
	public static final String TRANS_ICON_FILE = "/icon_trans.png";
	
	private static BlendState blendState;
	
	private LODNode lodNode;
	private BillboardNode bbNode;
	
	public BBNodeController(LODNode lodNode) {
		super(lodNode);
		this.lodNode = lodNode;

		if(blendState == null) {
			blendState = DisplaySystem.getDisplaySystem().getRenderer().createBlendState();
			blendState.setBlendEnabled(true);
			blendState.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
			blendState.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
			blendState.setTestEnabled(true);
			blendState.setTestFunction(BlendState.TestFunction.GreaterThan);
		}
	}
	
	private String getPickIconPath(ModelNode pick, boolean trans) {
		String image = null;
		if(pick instanceof TeamNode) {
			TeamNode pickedNode = (TeamNode)pick;
			if(pickedNode instanceof SpawnStation && pickedNode.getTeam() == null) 
				image = "data/models/spawnStation";
			else image = pickedNode.getFilePath();
		} else if(pick instanceof Asteroid) {
			String name = ((Asteroid)pick).getName().toLowerCase();
			image = "data/models/asteroids/" + name;
		}
		if(image == null) return null;
		image += "/" + (trans ? TRANS_ICON_FILE : ICON_FILE);
		return image;
	}
	
	@Override
	protected boolean ready() {
		return lodNode.getBBNodeBound() != null && lodNode.getBBNodeBound() instanceof BoundingBox;
	}
	
	@Override
	protected void performAction(float time) {
		bbNode = new BillboardNode("BillboardNode for " + lodNode.getName());
		BoundingBox bound = (BoundingBox)lodNode.getBBNodeBound();
		
		float factor = ((lodNode instanceof Asteroid) ? 0.09f : 3f);
		float width = (bound.xExtent < bound.zExtent ? bound.zExtent : bound.xExtent) * factor;
		float height = bound.yExtent * factor;
//		float width = bound.getRadius() * factor;
//		float height = width;
		
		Quad quad = new Quad("Quad for " + lodNode.getName(), width, height);
		bbNode.attachChild(quad);
		quad.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
		quad.setRenderState(TextureLoader.getTextureState(getPickIconPath(lodNode, true)));
		quad.setRenderState(blendState);
		bbNode.setLightCombineMode(LightCombineMode.Off);
		bbNode.updateRenderState();
		
		lodNode.setBillboardNode(bbNode);
	}
}